package org.cordova.plugin.jfyun;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.widget.Toast;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.GrammarListener;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.LexiconListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.util.ContactManager;
import com.iflytek.cloud.util.ContactManager.ContactListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

/**
 * cordova科大讯飞插件
 * create by wilhan.tian
 */
public class Jfyun extends CordovaPlugin {

    private Context context;

    public static CallbackContext callbackContext;
    private SpeechSynthesizer mTts;
    @Override
    protected void pluginInitialize() {
        super.pluginInitialize();
        context = cordova.getActivity();
        //SpeechUtility.createUtility(context, "appid=5ac34294");
        SpeechUtility.createUtility(context, SpeechConstant.APPID +"=5ac34294");
    }

  private void setSpeakParameter(){
    if (mTts==null){
      //1.创建SpeechSynthesizer对象, 第二个参数：本地合成时传InitListener
      mTts = SpeechSynthesizer.createSynthesizer(context, null);
      //2.合成参数设置，详见《科大讯飞MSC API手册(Android)》SpeechSynthesizer 类
      mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
      mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
      mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
      mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
      //设置合成音频保存位置（可自定义保存位置），保存在“./sdcard/iflytek.pcm”
      //保存在SD卡需要在AndroidManifest.xml添加写SD卡权限
      //如果不需要保存合成音频，注释该行代码
      mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
      //3.开始合成
      // mTts.startSpeaking("科大讯飞，让世界聆听我们的声音", mSynListener);
    }
  }


  private InitListener mInitListener = new InitListener() {

    @Override
    public void onInit(int code) {

      if (code != ErrorCode.SUCCESS) {
        Toast.makeText(context,"初始化失败，错误码：" + code,Toast.LENGTH_SHORT);
      }
    }
  };

  //合成监听器
  private SynthesizerListener mSynListener = new SynthesizerListener(){
    //会话结束回调接口，没有错误时，error为null
    public void onCompleted(SpeechError error) {
      if (error == null) {
//                showTip("播放完成");
        callbackContext.success("播放完成");
      } else if (error != null) {

        callbackContext.error(error.getPlainDescription(true));
      }
    }
    //缓冲进度回调
    //percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，endPos表示缓冲音频在文本中结束位置，info为附加信息。
    public void onBufferProgress(int percent, int beginPos, int endPos, String info) {}
    //开始播放
    public void onSpeakBegin() {

//            showTip("开始播放");
    }
    //暂停播放
    public void onSpeakPaused() {}
    //播放进度回调
    //percent为播放进度0~100,beginPos为播放音频在文本中开始位置，endPos表示播放音频在文本中结束位置.
    public void onSpeakProgress(int percent, int beginPos, int endPos) {}
    //恢复播放回调接口
    public void onSpeakResumed() {}
    //会话事件回调接口
    public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}
  };

  private void startSpeak(String speakMessage) {
    setSpeakParameter();
    if (mTts.isSpeaking()){
      mTts.stopSpeaking();
    }
    mTts.startSpeaking(speakMessage, mSynListener);

  }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext cb) throws JSONException {
        callbackContext=cb;
        if (action.equals("startListen")) {
            Intent intent = new Intent(context, JfyunDialog.class);
            cordova.getActivity().startActivity(intent);
            return true;
        }else if(action.equals("startSpeak")){

          String speakMessage = args.getString(0).trim();
          Toast.makeText(context, speakMessage, Toast.LENGTH_SHORT).show();
          startSpeak(speakMessage);

          return true;
        }
        return false;
    }





}
